import CoinItem from "./CoinItem";
import { LanguageManager } from "./language/LanguageManager";
import RESSpriteFrame from "./RESSpriteFrame";
import Anim from "./utils/Anim";
import EffectUtils from "./utils/EffectUtils";
import GuideEffect from "./utils/GuideEffect";
import MoneyChange from "./utils/MoneyChange";
import NotifyEffect from "./utils/NotifyEffect";
import Utils from "./utils/Utils";


interface posItem {
    x: number,
    y: number
}
interface nodeItem {
    hasContact: boolean,
    word: String,
    node: cc.Node
}
interface TargetItem {
    word: String,
    node: cc.Node,
    hasAnswer: boolean
}
const { ccclass, property } = cc._decorator;

@ccclass
export default class GameUI extends cc.Component {
    @property(cc.Label)
    private moneyLb: cc.Label = null
    @property(cc.Label)
    private horMoneyLb: cc.Label = null
    @property(cc.Node)
    private targetNode: cc.Node[] = []
    @property(cc.Node)
    private showNode: cc.Node = null
    @property(cc.Graphics)
    private LineGraphics: cc.Graphics = null
    @property(cc.Node)
    private contentNode: cc.Node = null
    @property(cc.Node)
    private moveNode: cc.Node = null
    @property(cc.Node)
    private tipFinger: cc.Node = null
    @property(cc.Node)
    private tipLine: cc.Node = null
    @property(cc.Node)
    private clickNodeArr: cc.Node[] = []
    @property(cc.Prefab)
    private labelPre: cc.Prefab = null
    //弹窗
    @property(cc.Node)
    private resultNode: cc.Node = null
    @property(cc.Node)
    private moneyNode: cc.Node = null
    @property(cc.Label)
    private resultMoneyLb: cc.Label = null
    @property(cc.ParticleSystem)
    private resultPar: cc.ParticleSystem = null
    @property(cc.Node)
    private resultBtn: cc.Node = null
    @property(cc.Node)
    private resultFinger:cc.Node = null

    private monerChange: MoneyChange = null
    private amount: number = 0
    private bgmAudioFlag: boolean = true
    private canPlayMusic: boolean = false
    private tipFillRange: number = 0
    private animFlag: boolean = true
    lastPos: posItem = null
    ctx: cc.Graphics = null
    canDraw: boolean = false
    public static maxDistance = 20
    nodeArr: nodeItem[] = []
    targetArr: TargetItem[] = []
    wordArr: any = []
    wordIndex: number = 0
    protected onLoad(): void {
        cc.director.getPhysicsManager().enabled = true
        // cc.director.getCollisionManager().enabledDebugDraw = true
        // cc.director.getCollisionManager().enabledDrawBoundingBox = true
    }
    protected start(): void {
        PlayerAdSdk.init();
        this.resize()
        let that = this;
        /**屏幕旋转尺寸改变 */
        cc.view.setResizeCallback(() => {
            that.resize();
        })
        cc.find('Canvas').on('touchstart', () => {
            this.canPlayMusic = true
            this.bgmAudioFlag && cc.audioEngine.play(RESSpriteFrame.instance.bgmAudioClip, false, 1)
            this.bgmAudioFlag = false
            this.unschedule(this.tipLineAnim)
            this.tipFinger.active = this.tipLine.active = false
        })
        this.resize()
        this.initData()
        this.monerChange = new MoneyChange(this.moneyLb, true, this.amount)
        this.horMoneyLb.string = `${LanguageManager.instance.getText(10001)}0.00`
        this.monerChange.prefix = LanguageManager.instance.getText(10001)
        let answerWordArr = ['N', 'E', 'T', 'T', 'N']
        for (let i = 0; i < this.targetNode.length; i++) {
            this.targetArr[i] = {
                node: this.targetNode[i],
                word: answerWordArr[i],
                hasAnswer: false
            }
        }
        // this.schedule(this.tipLineAnim, 1 / 60)
        this.tipLineAnim()
        this.contentNode.on(cc.Node.EventType.TOUCH_START, this.touchStartFunc, this)
    }
    private touchStartFunc(e) {
        this.contentNode.on(cc.Node.EventType.TOUCH_MOVE, this.LineEvent, this)
        this.contentNode.on(cc.Node.EventType.TOUCH_END, this.touchEndFunc, this)
    }
    private LineEvent(e) {
        let pos = e.getLocation()
        let movePos = this.moveNode.parent.convertToNodeSpaceAR(pos)
        this.moveNode.position = movePos
        if (!this.canDraw) {
            for (let i = 0; i < this.clickNodeArr.length; i++) {
                if (this.isNodeOverBox(this.moveNode, this.clickNodeArr[i])) {
                    this.canDraw = true
                    this.showNode.active = true
                    this.LineGraphics.node.position = movePos
                    this.LineGraphics.node.parent = this.clickNodeArr[i]
                    this.clickNodeArr[i].zIndex = 10
                    this.LineGraphics.node.x = 0
                    this.LineGraphics.node.y = 0
                    break;
                }
            }
        }
        if (this.canDraw) {
            pos = this.LineGraphics.node.parent.convertToNodeSpaceAR(pos)
            this.LineGraphics.lineWidth = 25
            this.LineGraphics.moveTo(this.lastPos.x, this.lastPos.y)
            this.lastPos.x = pos.x
            this.lastPos.y = pos.y
            this.LineGraphics.lineTo(pos.x, pos.y)
            this.LineGraphics.stroke()
        }
        for (let i = 0; i < this.clickNodeArr.length; i++) {
            if (this.isNodeOverBox(this.moveNode, this.clickNodeArr[i]) && !this.nodeArr[i].hasContact) {
                cc.audioEngine.play(RESSpriteFrame.instance.dingAudioClip,false,1)
                console.log(`接触到${i}`);
                this.nodeArr[i].hasContact = true
                this.wordArr.push(this.nodeArr[i])
                let lbNode = cc.instantiate(this.labelPre)
                lbNode.parent = this.showNode
                lbNode.active = true
                lbNode.getComponent(cc.Label).string = `${this.nodeArr[i].word}`
                break;
            }
        }
    }
    private touchEndFunc() {
        this.LineGraphics.clear()
        this.checkAnswer()
        console.log('enddd', this.wordArr);
        this.initData()
    }
    private checkAnswer() {
        let answer = ''
        let netArr = [0, 1, 2]
        let tenArr = [3, 1, 4]
        this.wordArr.forEach(item => {
            answer += `${item.word}`
        });
        let pos = null
        let nowNode = null
        let tempArr = null
        let showNodeArr = [...this.showNode.children]
        if (answer == 'TEN' || answer == 'NET') {
            tempArr = answer == 'NET' ? netArr : tenArr
            cc.audioEngine.play(RESSpriteFrame.instance.trueAudioClip,false,1)
            for (let i = 0; i < showNodeArr.length; i++) {
                console.log(this.targetArr[tempArr[i]], 'jayaa');
                this.targetArr[tempArr[i]].hasAnswer = true
                console.log(this.targetArr[tempArr[i]], 'jayaa');
                nowNode = showNodeArr[i]
                pos = nowNode.parent.convertToWorldSpaceAR(nowNode.position)
                pos = this.targetNode[tempArr[i]].parent.convertToNodeSpaceAR(pos)
                nowNode.parent = this.targetNode[tempArr[i]]
                nowNode.position = pos
                cc.tween(nowNode).delay(0.2 + i * 0.1)
                    .to(0.45, { x: 0, y: 5 }, { easing: 'quadOut' })
                    .call(() => {
                        cc.tween(this.targetNode[tempArr[i]].children[0])
                            .to(0.08, { scale: 1 })
                            .start()
                    })
                    .start()
            }
            this.amount = LanguageManager.instance.formatUnit(150)
            let isPass: boolean = true
            this.targetArr.forEach((item) => {
                if (!item.hasAnswer) {
                    isPass = false
                }
            })
            if (isPass) {
                this.amount = LanguageManager.instance.formatUnit(300)
                this.showUI()
            }
            Utils.SetScale(this.moneyLb.node,1.25,0.3,false,2)
            Utils.SetScale(this.horMoneyLb.node,1.25,0.3,false,2)
            this.moneyLb.string = `${this.monerChange.prefix}${this.amount}.00`
            this.horMoneyLb.string = `${this.monerChange.prefix}${this.amount}.00`
        } else {
            cc.audioEngine.play(RESSpriteFrame.instance.wrongUpAudioClip,false,1)
        }
    }
    private showUI(){
        NotifyEffect.NormalShowUI(this.resultNode,RESSpriteFrame.instance.comeOutAudioClip,1.2,true,1,1,0.3,0.3,(()=>{
            cc.audioEngine.play(RESSpriteFrame.instance.cherrUpAudioClip,false,1)
            this.moneyNode.scale = 2
            cc.tween(this.moneyNode)
            .to(0.4,{scale:1},{easing:'quadOut'})
            .call(()=>{
                this.resultPar.node.active = true
                this.resultBtn.scale = 2.5
                cc.tween(this.resultBtn)
                .to(0.3,{scale:1},{easing:'quadOut'})
                .call(()=>{
                    Utils.SetScale(this.resultBtn,1.1,0.3,true)
                    this.resultFinger.active = true
                })
                .start()
            })
            .start()
        }))
    }
    private initData() {
        if (this.showNode.children.length) {
            this.showNode.removeAllChildren()
        }
        this.lastPos = {
            x: 0,
            y: 0
        }
        this.wordIndex = 0
        this.canDraw = false
        let wordArr = ['N', 'E', 'T']
        for (let i = 0; i < this.clickNodeArr.length; i++) {
            this.nodeArr[i] = {
                hasContact: false,
                word: wordArr[i],
                node: this.clickNodeArr[i]
            }
            this.clickNodeArr[i].zIndex = 0
        }
        this.wordArr = []
        this.showNode.active = false
        this.showNode.children.forEach((item) => {
            item.active = false
            item.getComponent(cc.Label).string = ``
        })
    }
    private isNodeOverBox(nodeA: cc.Node, nodeB: cc.Node) {
        let nodeABox = nodeA.getBoundingBoxToWorld()
        let nodeBBox = nodeB.getBoundingBoxToWorld()
        return nodeABox.intersects(nodeBBox)
    }
    private tipLineAnim() {
        cc.tween(this.tipLine).repeatForever(
            cc.tween(this.tipLine)
            .to(0.4,{opacity:0})
            .to(0.4,{opacity:255})
            .start()
        ).start()
        // if (this.animFlag) {
        //     if (this.tipFillRange >= 1) {
        //         this.animFlag = false
        //         this.tipFillRange = 0
        //         setTimeout(() => { this.animFlag = true }, 680)
        //     }
        //     this.tipFillRange += 0.025
        //     this.tipLine.getComponent(cc.Sprite).fillRange = this.tipFillRange
        // }
    }
    private getRandomInt(min: number, max: number) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    private resize() {
        const canvasValue: any = cc.Canvas.instance;
        let frameSize = cc.view.getFrameSize();
        let isVerTical = cc.winSize.height > cc.winSize.width
        if (isVerTical) {//竖屏
            if (cc.winSize.width / cc.winSize.height > 0.7) {
                cc.Canvas.instance.fitHeight = true;
                cc.Canvas.instance.fitWidth = false;
            } else {
                cc.Canvas.instance.fitHeight = false;
                cc.Canvas.instance.fitWidth = true;
            }
        } else {
            cc.Canvas.instance.fitHeight = true;
            cc.Canvas.instance.fitWidth = false;
        }
        cc.director.getScene().getComponentsInChildren(cc.Widget).forEach(function (t) {
            t.updateAlignment()
        });
    }
    private cashoutFunc() {
        console.log('跳转');
        this.canPlayMusic && cc.audioEngine.play(RESSpriteFrame.instance.clickAudioClip, false, 1)
        PlayerAdSdk.gameEnd()
        PlayerAdSdk.jumpStore()
    }
    protected onDisable(): void {

    }
}   
